package com.fbty.mt.timer;

import java.util.List;

import com.fbty.mt.domain.CheckInfo;
import com.fbty.mt.domain.IpInfo;
import com.fbty.mt.service.IpService;
import com.fbty.mt.service.ProxyService;
import com.fbty.mt.utils.StaticValue;

public class UpdateIpInfoTimer implements Runnable{
	private IpService ipInfoService;
	private ProxyService proxyService;
	/**
	 * 从数据库中取出数据，然后进行扫描，放到scanedIpInfoes
	 * @throws Exception
	 */
	public void scanService() throws Exception{
		List<IpInfo> list = ipInfoService.getAllIpInfoes();
		System.out.println("当前内存中存在："+list.size()+"条数据！");
		scanDelay(list);
	}
	/**
	 * 迭代扫描所有的ip,完成后放到scanedIpInfoes里面
	 * @param list
	 */
	private void scanDelay(List<IpInfo> list) {
		int index = 0;
		for(IpInfo ipInfo : list) {
			Integer  type = 0;
			if("socks5".equalsIgnoreCase(ipInfo.getType())) {
				type = CheckInfo.SOCKS5_PROXY;
			} else if("socks4".equalsIgnoreCase(ipInfo.getType())) {
				type = CheckInfo.SOCKS4_PROXY;
			} if("http".equalsIgnoreCase(ipInfo.getType())) {
				type = CheckInfo.HTTP_PROXY;
			} if("https".equalsIgnoreCase(ipInfo.getType())) {
				type = CheckInfo.HTTPS_PROXY;
			} 
			System.out.println("第"+index+"条："+ipInfo);
			index++;
			CheckInfo info = proxyService.checkConnection(ipInfo.getIp(), Integer.parseInt(ipInfo.getPort()), type);
//			/** 本地服务器到代理服务器的延迟*/
//			private long delay;
//			/**代理服务器地址*/
//			private String host;
//			/** 监测代理类别*/
//			private int checkType;
//			/** 监测结果*/
//			private int reslut;
//			/**端口*/
//			private int port;
			if(info.getReslut() != 0) {
				int state = ipInfo.getState()+1;
				ipInfo.setSpeed("---");
				ipInfo.setState(state);
			} else {
				ipInfo.setState(ipInfo.getState());
				ipInfo.setSpeed(info.getDelay()+"");
			}
			StaticValue.scanedIpInfoes.add(ipInfo);
		}
	}
	
	@Override
	public void run() {
		List<IpInfo> list = StaticValue.scanedIpInfoes.subList(0, 50);
		ipInfoService.saveIpInfos(list);
		StaticValue.scanedIpInfoes.removeAll(list);
		System.out.println("扫描后，内存中还存在："+StaticValue.scanedIpInfoes.size()+"要记录！");
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public IpService getIpInfoService() {
		return ipInfoService;
	}
	public void setIpInfoService(IpService ipInfoService) {
		this.ipInfoService = ipInfoService;
	}
	public ProxyService getProxyService() {
		return proxyService;
	}
	public void setProxyService(ProxyService proxyService) {
		this.proxyService = proxyService;
	}
	
}
